package com.ecmcloud.flow.node.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.ecmcloud.common.constants.ProcessInstanceConstant;
import com.ecmcloud.common.dto.flow.Node;
import com.ecmcloud.common.dto.flow.NodeUser;
import com.ecmcloud.common.dto.third.DeptDto;
import com.ecmcloud.common.utils.JsonMapperUtils;
import com.ecmcloud.flow.node.AssignUserStrategy;
import com.ecmcloud.flow.utils.BizHttpUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 来自表单部门
 */
@Component
public class AssignDeptFormStrategyImpl implements InitializingBean, AssignUserStrategy {
	
    @Override
    public List<String> handle(Node node, NodeUser rootUser, Map<String, Object> variables) {
        Set<String> assignList = Sets.newConcurrentHashSet();
        //表单值
        Object variable = variables.get(node.getFormUserId());
        if (Objects.nonNull(variable)) {
            String deptUserType = node.getDeptUserType();
            String jsonString = JsonMapperUtils.toJsonString(variable);
            List<NodeUser> nodeUserDtoList = JsonMapperUtils.getInstance().parseObject(jsonString, new TypeReference<List<NodeUser>>() {});
            List<String> deptIdList = nodeUserDtoList.stream().map(w -> String.valueOf(w.getId())).collect(Collectors.toList());

            if (!StrUtil.equals(deptUserType, ProcessInstanceConstant.AssignedTypeFormDeptUserTypeClass.ALL_USER)) {
                List<DeptDto> deptDtos = BizHttpUtil.queryDeptList(deptIdList);
                for (DeptDto deptDto : deptDtos) {
                    List<String> leaderUserIdList = deptDto.getLeaderUserIdList();
                    if (CollUtil.isNotEmpty(leaderUserIdList)) {
                        assignList.addAll(leaderUserIdList);
                    }
                }
            } else {
                List<String> userIdList = BizHttpUtil.queryUserIdListByDepIdList(deptIdList).getData();
                assignList.addAll(userIdList);
            }
        }
        return Lists.newArrayList(assignList);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        afterPropertiesSet(ProcessInstanceConstant.AssignedTypeClass.FORM_DEPT);
    }
}
